package com.itheima.reggie.exception;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerException(SQLIntegrityConstraintViolationException exception){
        exception.printStackTrace();
        String message = exception.getMessage();
        String username = message.split(" ")[2].replace("'", "");
        return R.error(username +"已存在");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> handlerException(CustomException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
